package org.jeecg.modules.demo.soFeiyong.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.cwSaleInvoice.service.ICwSaleInvoiceService;
import org.jeecg.modules.demo.soFeiyong.entity.SoFeiyong;
import org.jeecg.modules.demo.soFeiyong.service.ISoFeiyongService;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 销售费用单
 * @Author: jeecg-boot
 * @Date: 2022-01-18
 * @Version: V1.0
 */
@Api(tags = "销售费用单")
@RestController
@RequestMapping("/sale/soFeiyong")
@Slf4j
public class SoFeiyongController extends JeecgController<SoFeiyong, ISoFeiyongService> {
    @Autowired
    private ISoFeiyongService soFeiyongService;
    @Autowired
    private ICwSaleInvoiceService cwSaleInvoiceService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISoSaleOrderService soSaleOrderService;

    private static final String TITLE = "单据审核";


    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的销售费用单需要您的审核，请及时查看！";
        return str;
    }
    /**
     * 分页列表查询
     *
     * @param soFeiyong
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "销售费用单-分页列表查询")
    @ApiOperation(value = "销售费用单-分页列表查询", notes = "销售费用单-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="yunxiao/soFeiyong/SoFeiyongList")
    public Result<?> queryPageList(SoFeiyong soFeiyong,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SoFeiyong> queryWrapper = QueryGenerator.initQueryWrapper(soFeiyong, req.getParameterMap());
        queryWrapper.eq("IS_DELETE", 0);
        Page<SoFeiyong> page = new Page<SoFeiyong>(pageNo, pageSize);
        IPage<SoFeiyong> pageList = soFeiyongService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param soFeiyong
     * @return
     */
    @AutoLog(value = "销售费用单-添加")
    @ApiOperation(value = "销售费用单-添加", notes = "销售费用单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SoFeiyong soFeiyong,HttpServletRequest req) {
        try {



            String max_code = soFeiyongService.getMaxCode();
            Map<String,String> codeMap = new HashMap<>();
            if(max_code == null){
                codeMap.put("maxCode",null);
            }else{
                codeMap.put("maxCode",max_code);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderService.getTname(tenantId);
            String name = tname+"FT_";
            String resultCode = generateOddUtil.createCode(codeMap,name);
            soFeiyong.setSoFyNo(resultCode);

            soFeiyong.setCreateTime(new Date());
            soFeiyong.setIsDelete(0);
            soFeiyong.setShenhe(0);
            soFeiyong.setIsFt(0);
            soFeiyong.setSyFtjine(soFeiyong.getPsAmount());
            if (soFeiyong.getSofDate() == null){
                soFeiyong.setSofDate(new Date());
            }
            soFeiyongService.save(soFeiyong);


            LoginUser user = sysBaseAPI.getUserById(soFeiyong.getSalesStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(soFeiyong.getShName()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
            templateParam.put("checkOrder",soFeiyong.getSoFyNo());
            templateParam.put("cd_url","/yunxiao/soFeiyong/SoFeiyongList");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);
            return Result.OK("生成费用单成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }



    /**
     * 编辑
     *
     * @param soFeiyong
     * @return
     */
    @AutoLog(value = "销售费用单-编辑")
    @ApiOperation(value = "销售费用单-编辑", notes = "销售费用单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SoFeiyong soFeiyong) {
        soFeiyong.setSyFtjine(soFeiyong.getPsAmount());
        soFeiyongService.updateById(soFeiyong);
        return Result.OK("编辑成功!");
    }

    //审核
    @PutMapping(value = "/editShenhe")
    public Result<?> editShenhe(@RequestBody SoFeiyong soFeiyong) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (!soFeiyong.getShName().equals(sysUser.getId())){
            return Result.error(300,"您不是当前单据的指定审核人！");
        }
        if (soFeiyong.getShenhe() == 1) {
//            soFeiyong.setShName(sysUser.getRealname());
            soFeiyong.setShTime(new Date());
        } else {
//            soFeiyong.setShName("");
            soFeiyong.setShTime(null);
        }
        soFeiyongService.updateById(soFeiyong);
        return Result.OK("审核成功!");
    }

    //绑定费用分摊金额到发票
    @PutMapping(value = "/buildFt")
    public Result<?> buildFt(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
        System.out.println(jsonObject);
        System.out.println("-------------------------");
        if (soFeiyongService.buildFt(jsonObject,req)) {
            return Result.OK("分摊成功！");
        }
        return Result.error("分摊失败!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售费用单-通过id删除")
    @ApiOperation(value = "销售费用单-通过id删除", notes = "销售费用单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        soFeiyongService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "销售费用单-批量删除")
    @ApiOperation(value = "销售费用单-批量删除", notes = "销售费用单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.soFeiyongService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售费用单-通过id查询")
    @ApiOperation(value = "销售费用单-通过id查询", notes = "销售费用单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SoFeiyong soFeiyong = soFeiyongService.getById(id);
        if (soFeiyong == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(soFeiyong);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param soFeiyong
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SoFeiyong soFeiyong) {
        return super.exportXls(request, soFeiyong, SoFeiyong.class, "销售费用单");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SoFeiyong.class);
    }

}
